<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VSelect
          v-model="form.platform_ids"
          placeholder="平台"
          :options="options.platform"
          multiple
          collapse-tags
          style="min-width: 160px"
        />
        <VSelect
          v-model="form.shop_ids"
          placeholder="店铺"
          :options="options.shop"
          multiple
          collapse-tags
          style="min-width: 160px"
          paste="店铺名称"
        />
        <VSelect
          v-model="form.company_ids"
          placeholder="公司名称"
          :options="options.company"
          multiple
          collapse-tags
          style="min-width: 160px"
        />
        <el-input
          v-model="form.now_service_provider"
          placeholder="现服务商"
          class="w-52"
        />
        <VSelect
          v-model="form.statuses"
          placeholder="状态"
          :options="options.status"
          multiple
          collapse-tags
          style="min-width: 160px"
        />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 130px">
            <el-option
              label="VAT证书日期"
              value="vat_certificate_date"
            ></el-option>
            <el-option
              label="德国本地日期"
              value="german_local_date"
            ></el-option>
            <el-option
              label="提交申请时间"
              value="submit_apply_date"
            ></el-option>
            <el-option
              label="欧盟EORI生效日期"
              value="eu_eori_effective_date"
            ></el-option>
          </el-select>
          <el-date-picker
            v-model="form.dateRange.value"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="max-width: 260px"
          />
        </VGroup>
        <VGroup>
          <el-select v-model="form.input.type" style="width: 136px">
            <el-option label="VAT税号" value="vat_num"></el-option>
            <el-option
              label="德国本地税号"
              value="german_local_tax_num"
            ></el-option>
            <el-option label="所在国VAT" value="vat_country"></el-option>
            <el-option label="EORI Number" value="eu_eori_num"></el-option>
          </el-select>
          <el-input
            v-model="form.input.value"
            placeholder="请输入"
            class="w-60"
          />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton
          auth="/base/vat/create"
          type="primary"
          @click="create(tableRef)"
        >
          <template #icon>
            <svg-icon icon-class="add"/>
          </template>
          添加
        </VButton>
        <VButton
          auth="/base/vat/delete"
          @click="handleBatch('delete')"
          >
           <template #icon>
            <svg-icon icon-class="del"/>
          </template>
          删除
          </VButton
        >
        <VImport
          :tableRef="tableRef"
          importUrl="/v1/vat/import"
          v-if="authList.includes('/base/vat/import')"
          downloadUrl="https://xc-base.oss-cn-shenzhen.aliyuncs.com/template/vat.xlsx"
          class="ml-auto"
        />
        <VExport
          auth="/purchase/manage/bill/export"
          mainKey="vat_id"
          name="vat"
          :tableRef="tableRef"
          task
        />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <Bind ref="bindRef" />
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import api from "./api.js";
import Add from "./components/add.vue";
import Bind from "./components/bind.vue";
import VImport from "./components/ImportDialog";
import VExport from "./components/ExportDialog";
import { getBaseOption } from "@/api/public";
import { ElMessage, ElMessageBox } from "element-plus";

const baseName = "vat";
const tableRef = ref();
const loadings = reactive({});

const authList = window.BTN_AUTH;
// 查询
const query = () => {
  tableRef?.value.query();
};

// 新增
const addRef = ref();
const create = () => {
  addRef?.value.open();
};

// 获取options
const options = ref({});
Promise.all([
  getBaseOption({ type: baseName }).then((res) => res.data),
  Promise.resolve({ test: [{ label: "没有数据", value: 1 }] }),
]).then((res) => {
  options.value = res.reduce(
    (acc, cur) => ((acc = { ...acc, ...cur }), acc),
    {}
  );
});

// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords();
  if (!selection.length) {
    ElMessage.warning("请先选择行");
    return;
  }
  const vat_ids = selection.map((d) => d.vat_id);
  const showLoading = () => (loadings[name] = true);
  const closeLoading = () => (loadings[name] = false);
  const handle = {
    delete: () => {
      ElMessageBox.confirm("是否确认删除？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          showLoading();
          api
            .delete({ vat_ids })
            .then((res) => {
              ElMessage({ type: "success", message: "操作成功" });
              query();
            })
            .finally(closeLoading);
        })
        .catch(() => {
          ElMessage({ type: "info", message: "取消操作" });
        });
    },
  };
  handle[name]();
};
// 单行操作
const bindRef = ref();
const handleRow = (name, row, rowIndex) => {
  const { vat_id } = row;
  const showLoading = (name = "handle") => {
    loadings[name + rowIndex] = true;
  };
  const closeLoading = (name = "handle") => {
    loadings[name + rowIndex] = false;
  };
  const handle = {
    edit: () => {
      addRef?.value.open(vat_id);
    },
    delete: () => {
      ElMessageBox.confirm("是否确认删除？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          showLoading();
          api
            .delete({ vat_ids: [vat_id] })
            .then((res) => {
              ElMessage({ type: "success", message: "操作成功" });
              query();
            })
            .finally(closeLoading);
        })
        .catch(() => {
          ElMessage({ type: "info", message: "取消操作" });
        });
    },
    bind: () => {
      bindRef?.value.open(vat_id);
    },
  };
  handle[name]();
};

// 列表配置
const tableOptions = reactive({
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: "vat_num", value: "" }, // 组合
      dateRange: { type: "vat_certificate_date", value: [], range: true }, // 组合
    },
  },
  columns: [
    { type: "checkbox", fixed: "left", width: 40 },
    { type: "seq", fixed: "left", width: 50, slots: { header: () => "序号" } },
    {
      field: "",
      minWidth: 220,
      slots: {
        header: () => "VAT税号/VAT证书日期",
        default: ({ row }) => (
          <div>
            <VText value={row.vat_num}></VText>
            <VText value={row.vat_certificate_date}></VText>
          </div>
        ),
      },
    },
    {
      field: "",
      minWidth: 220,
      slots: {
        header: () => (
          <div>
            德国本地税号
            <br />
            德国本地日期
          </div>
        ),
        default: ({ row }) => (
          <div>
            <VText value={row.german_local_tax_num}></VText>
            <VText value={row.german_local_date}></VText>
          </div>
        ),
      },
    },
    { title: "所在国VAT", field: "vat_country", minWidth: 140 },
    {
      title: "公司名称",
      field: "company_name_ch",
      minWidth: 140,
      line: 2,
    },
    { title: "业务负责人", field: "business_owner_name", minWidth: 140 },
    { title: "提交申请时间", field: "submit_apply_date", minWidth: 170 },
    {
      title: "关联店铺",
      field: "assoc_shops",
      minWidth: 170,
      slots: {
        default: ({ row }) =>
          row.assoc_shops ? (
            authList.includes("/base/vat/shop-list") ? (
              <el-button
                link
                type="primary"
                onClick={() => handleRow("bind", row)}
              >
                {row.assoc_shops}
              </el-button>
            ) : (
              row.assoc_shops
            )
          ) : (
            0
          ),
      },
    },
    {
      field: "",
      minWidth: 220,
      slots: {
        header: () => (
          <div>
            欧盟EORI Number
            <br />
            EORI生效日期
          </div>
        ),
        default: ({ row }) => (
          <div>
            <VText value={row.eu_eori_num}></VText>
            <VText value={row.eori_effective_date}></VText>
          </div>
        ),
      },
    },
    {
      title: "服务商（转）",
      field: "now_service_provider",
      minWidth: 140,
      slots: {
        default: ({ row }) => (
          <div>
            <VText value={row.now_service_provider} line={3} />
          </div>
        ),
      },
    },
    {
      title: "转服务商日期",
      field: "switch_service_provider_date",
      minWidth: 170,
    },
    { title: "申报周期", field: "reporting_period", minWidth: 120 },
    { title: "续费周期", field: "existence_period", minWidth: 120 },
    {
      title: "价格",
      field: "fee",
      minWidth: 100,
    },
    {
      title: "状态",
      minWidth: 100,
      slots: {
        default: ({ row }) => row.status,
      },
    },
    {
      title: "备注",
      field: "remark",
      minWidth: 120,
      line: 3,
    },
    {
      title: "操作",
      width: 110,
      fixed: "right",
      slots: {
        default: ({ row, rowIndex }) => {
          return (
            <div>
              <VButton
                auth="/base/vat/edit"
                link
                type="primary"
                onClick={() => handleRow("edit", row)}
              >
                编辑
              </VButton>
              <VButton
                auth="/base/vat/delete"
                link
                type="danger"
                onClick={() => handleRow("delete", row, rowIndex)}
              >
                删除
              </VButton>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page }),
    },
  },
});
</script>
